package com.controller;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/con")
public class ConsumerController {

    private String message = "";

    @RequestMapping("/receive")
    public String receive() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.159.142");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel();) {
            channel.queueDeclare("woniu12", false, false, false, null);
            System.out.println("消费者等待接收消息...");
            /*
             * 消费队列种的消息
             * 1. queue_name
             * 2. xx
             * 3. DeliverCallback : 包含了mq队列中的消息。这个相当于是一个存放消息的容器，我们消费者要提供这个容器，消息是由MQ来帮助我们装的。
             * 4. CancelCallback : 取消，回调这个对象
             */
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                message = new String(delivery.getBody(), "UTF-8");
                System.out.println("消费者接收到队列的消息：" + message);
            };
            // 消费队列
            channel.basicConsume("woniu12", true, deliverCallback, consumerTag -> {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "完成消费";
    }
}
